//
// Created by kyle on 25-7-16.
//

#ifndef TEXTRENDERER_H
#define TEXTRENDERER_H

#include <iostream>
#include <string>
#include <vector>
#include <cctype>
#include <cstdint>
#include <algorithm>
#include <ft2build.h>
#include FT_FREETYPE_H
#include <filesystem>
#include <memory>
#include <unordered_map>

#include "FontMetricsTool.h"
#include "FontRenderer.h"
#include "FrameBuffer.h"
#include "TextObject.h"
#include "util.h"

namespace fs = std::filesystem;

// 文本渲染器类
class TextRenderer {
public:
    enum class Orientation {
        Horizontal,
        Vertical
    };

    TextRenderer()
        : fb_(std::make_shared<FrameBuffer>()),
          font_renderer_(std::make_unique<FontRenderer>()) {
    }

    //初始化屏幕
    void init_frame();

    /**
     * 最重要的渲染函数
     * @param text
     * @param x
     * @param y
     * @param color
     * @param font_size
     * @param contain
     * @param orientation
     */
    void render_text(const std::string &text, int x, int y, uint16_t color,
                     int font_size, bool contain, Orientation orientation);

    void display() const;

private:
    std::shared_ptr<FrameBuffer> fb_;
    std::unique_ptr<FontRenderer> font_renderer_;

    bool initialized_ = false;

    /**
     * 确保初始化
     */
    void ensure_initialized();

    int calculate_max_font_size(const std::string &text, int start_x, int start_y, Orientation orientation);

    bool can_fit_text(const std::string &text, int start_x, int start_y, int font_size, Orientation orientation);

    void render_horizontal(const std::string &text, int start_x, int start_y,
                           uint16_t color, int font_size);

    void render_vertical(const std::string &text, int start_x, int start_y,
                         uint16_t color, int font_size);

    void render_ellipsis(int x, int y, uint16_t color, int font_size);

    static size_t decode_utf8(const std::string &str, size_t pos, uint32_t &out);
};


#endif //TEXTRENDERER_H
